<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    @load="onLoad"
    :immediate-check="false"
  >
    <van-cell v-for="(item, index) in list" :key="index" :title="item.title" />
  </van-list>
</template>

<script>
import { getSearchRes } from '@/api/search'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      pre_page: 10,
      error: false
    }
  },
  props: ['searchText', 'isSearch'],
  created () {},
  watch: {
    isSearch (val) {
      if (val) {
        this.page = 1
        this.list = []
        this.onLoad()
        this.finished = false
      }
    },
    list () {
      if (!this.finished) {
        if (this.list.length <= 15) {
          this.onLoad()
        }
      }
    }
  },
  methods: {
    async onLoad () {
      try {
        // 1.发送请求
        const res = await getSearchRes({
          page: this.page,
          pre_page: this.pre_page,
          q: this.searchText
        })
        // 2.本地赋值
        this.list.push(...res.data.data.results)
        this.loading = false
        // 4.判断是否还有数据
        if (res.data.data.results.length !== 0) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>
<style scoped lang="less"></style>
